package org.wiztools.thegreatwall;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.wiztools.commons.DigestUtil;

/**
 *
 * @author subwiz
 */
public class AddUserServlet extends HttpServlet {

    private static final Logger LOG = Logger.getLogger(AddUserServlet.class.getName());

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        final List<String> errors = new ArrayList<String>();
        final String username = req.getParameter("username");
        final String password = req.getParameter("password");
        final String email = req.getParameter("email");
        final String firstName = req.getParameter("fname");
        final String lastName = req.getParameter("lname");

        // Create the user object:
        User user = new User();
        user.setUserName(username);
        user.setPassword(DigestUtil.sha256hex(password));
        user.setEmail(email);
        user.setFirstName(firstName);
        user.setLastName(lastName);
        LOG.info("user: " + user);

        //Set Error msg:
        String eMailMsg = (Validator.validEmail(email) ? null : "Email id is not in the correct format.");
        String fNameMsg = (Validator.validName(firstName) ? null : "Enter your first name correctly.");
        String lNameMsg = (Validator.validName(lastName) ? null : "Enter your last name correctly.");

        //Add in errors list:
        if (eMailMsg != null) {
            errors.add(eMailMsg);
        }
        if (fNameMsg != null) {
            errors.add(fNameMsg);
        }
        if (lNameMsg != null) {
            errors.add(lNameMsg);
        }

        req.setAttribute("user", user);

        //Dispatch:
        if (errors.size() == 0) {
            try {
                new MySQLOperations().addUser(user);
            } catch (OperationException ex) {
                errors.add(ex.getMessage());
                LOG.log(Level.SEVERE, null, ex);
            }
            req.setAttribute("errors", errors.size() > 0 ? errors : null);
            doGet(req, resp);
        } else {
            req.setAttribute("errors", errors);
            req.getRequestDispatcher("/adduser.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.getRequestDispatcher("/walls").forward(req, resp);
    }

}
